﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BLL;
using DLL;
using System.Windows.Forms.VisualStyles;
using QuanLyBanLe.Admin;
using CommonHelpers;
using Logging;
using System.Drawing.Printing;
using System.Configuration;
using Core;
using QuanLyBanLe.Constants;

namespace QuanLyBanLe
{
    public partial class FormInProdPaper : Form
    {
        private ProductService m_ProductService;
        private ProductTypeService m_ProductTypeService;
        private ProducerService m_ProducerService;
        private InProductService m_InProductService;

        private IList<Producer> m_Producers;
        private IList<ProductType> m_ProductTypes;
        private IList<Product> m_Products;
        private IList<Product> m_NewProducts;

        private bool isError = false;
        private int m_InProdPaperId = 0;
        private DateTime m_InputDate;
        private bool m_LoadComplete;
        private bool m_IsUpdatedMode;
        private bool m_EnabledEvent;
        private bool m_DataChanged;
        private const int SpaceSize = 110;
        private const int LabelHeight = 108;
        private const int LabelWidth = 135;
        private int m_Copies;
        private bool m_ProductItemHasListPrice;
        private Image m_BarCodeImage;
        private List<pInProdDetail_Get_Result> m_InProdDetails;
        private SortOrder m_SortOrder;
        private string m_SortColumn;
        private FormMode m_Mode;
        private int m_PaperId;
        // New mode
        public FormInProdPaper()
        {
            m_ProductService = new ProductService();
            m_ProductTypeService = new ProductTypeService();
            m_ProducerService = new ProducerService();
            m_InProductService = new InProductService();
            InitializeComponent();
            m_LoadComplete = true;
            m_IsUpdatedMode = false;
            m_EnabledEvent = false;
            m_DataChanged = false;
            dtgProduct.AutoGenerateColumns = false;
            lblTotal.Text = "0 Đ";
            InitData();
            m_ProductItemHasListPrice = false;
            m_Mode = FormMode.ADD;
        }
        // View mode
        public FormInProdPaper(int paperId, DateTime inputDate)
        {
            m_ProductService = new ProductService();
            m_ProductTypeService = new ProductTypeService();
            m_ProducerService = new ProducerService();
            m_InProductService = new InProductService();
            InitializeComponent();
            dtgProduct.AutoGenerateColumns = false;
            dtgProduct.Columns["colAmount"].ReadOnly = true;
            dtgProduct.Columns["colAmount"].Width = 170;
            dtgProduct.Columns["colInputPrice"].ReadOnly = true;
            dtgProduct.Columns["colInputPrice"].Width = 170;
            dtgProduct.Columns["colTotal"].Width = 170;
            m_InputDate = inputDate;
            dtgProduct.Columns["colProduct"].Width = 200;
            dtgProduct.Columns["colDelete"].Visible = false;
            dtgProduct.Columns["colProducer"].Visible = false;
            dtgProduct.Columns["colProductType"].Visible = false;
            dtgProduct.AllowUserToAddRows = false;
            m_IsUpdatedMode = true;
            m_EnabledEvent = false;
            m_DataChanged = false;
            lblTotal.Text = "0 Đ";
            InitData();
            m_PaperId = paperId;
            m_InProdDetails = m_InProductService.GetInProdDetails(m_PaperId);
            m_Mode = FormMode.VIEW;
            BindDetailsData();
            m_LoadComplete = true;
        }
        // Update mode
        public FormInProdPaper(int paperId, DateTime inputDate, bool isUpdated)
        {
            m_ProductService = new ProductService();
            m_ProductTypeService = new ProductTypeService();
            m_ProducerService = new ProducerService();
            m_InProductService = new InProductService();
            InitializeComponent();
            dtgProduct.AutoGenerateColumns = false;
            m_InputDate = inputDate;
            m_InProdPaperId = paperId;
            m_IsUpdatedMode = isUpdated;
            m_EnabledEvent = false;
            m_DataChanged = false;
            btnUpdate.Visible = true;
            btnUpdate.Enabled = false;
            lblTotal.Text = "0 Đ";
            InitData();
            m_PaperId = paperId;
            m_InProdDetails = m_InProductService.GetInProdDetails(m_PaperId);
            m_Mode = FormMode.UPDATE;
            BindDetailsDataForUpdate();
            m_LoadComplete = true;
        }

        #region DatagridView events        
        private void dtgProduct_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == dtgProduct.Columns["colDelete"].Index && e.RowIndex != -1)
                {
                    int returnValue = 1;
                    int id = Convert.ToInt32(dtgProduct["colId", e.RowIndex].Value);
                    if (id != 0)
                    {
                        returnValue = m_InProductService.DeleteInProdDetail(id);
                    }
                    if (returnValue == 0)
                    {
                        MessageBox.Show("Sản phẩm đã được bán nên không thể xóa");
                    }
                    else
                    {
                        dtgProduct.Rows.RemoveAt(e.RowIndex);
                        CalculateTotalAmount();
                    }
                }
                if (e.ColumnIndex == dtgProduct.Columns["colPrintBarcode"].Index && e.RowIndex != -1)
                {
                    int id = Convert.ToInt32(dtgProduct["colId", e.RowIndex].Value);
                    if (id != 0)
                    {
                        int productId = Convert.ToInt32(dtgProduct["colProduct", e.RowIndex].Value);
                        int amount = Convert.ToInt32(dtgProduct["colAmount", e.RowIndex].Value);
                        var product = m_Products.Where(x => x.Id == productId).FirstOrDefault();
                        if (product.SalePrice.HasValue)
                        {
                            string code = "";
                            m_BarCodeImage = BarCode.CreateBarCode(productId.ToString(), product.Name, product.SalePrice, product.ListedPrice, ref code, FormMain.s_OS);
                            if (product.ListedPrice.HasValue && product.ListedPrice > 0)
                            {
                                m_ProductItemHasListPrice = true;
                            }
                            else
                            {
                                m_ProductItemHasListPrice = false;
                            }
                            PrintBarCode(amount);
                        }
                        else
                        {
                            MessageBox.Show("Chưa nhập giá bán cho sản phẩm");
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                MyLogger.LogException("Error in FormInProdPaper : ", ex);
                MessageBox.Show("Có lỗi xảy ra");
            }
        }

        private void dtgProduct_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            int currentColumnIndex = dtgProduct.CurrentCell.ColumnIndex;
            if (e.Control is ComboBox)
            {
                var cbo = e.Control as ComboBox;

                cbo.DropDownStyle = ComboBoxStyle.DropDown;
                cbo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                cbo.AutoCompleteSource = AutoCompleteSource.ListItems;
                cbo.KeyDown -= new KeyEventHandler(cbo_KeyDown);
                cbo.KeyDown += new KeyEventHandler(cbo_KeyDown);

                if (currentColumnIndex == dtgProduct.Columns["colProduct"].Index)
                {
                    var m_ProductComboBox = cbo;
                    // To avoid register twice, remove handler before register
                    m_ProductComboBox.SelectedIndexChanged -= new EventHandler(m_ProductComboBox_SelectedIndexChanged);
                    m_ProductComboBox.SelectedIndexChanged += new EventHandler(m_ProductComboBox_SelectedIndexChanged);
                }
            }
            if (dtgProduct.CurrentCell.ColumnIndex == dtgProduct.Columns["colInputPrice"].Index ||
                dtgProduct.CurrentCell.ColumnIndex == dtgProduct.Columns["colAmount"].Index)
            {
                TextBox item = e.Control as TextBox;
                if (item != null)
                {
                    item.KeyPress -= new KeyPressEventHandler(item_KeyPress);
                    item.KeyPress += new KeyPressEventHandler(item_KeyPress);
                }
            }
        }

        private void cbo_KeyDown(object sender, KeyEventArgs e)
        {
            ComboBox cbo = sender as ComboBox;
            if (cbo.DroppedDown)
            {
                cbo.DroppedDown = false;
            }
        }

        private void m_ProductComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cbo = sender as ComboBox;
            if (m_EnabledEvent && dtgProduct.CurrentCell != null
                 && cbo.SelectedIndex > -1 && cbo.SelectedValue is int
                 && ((dtgProduct.CurrentCell.Value == null && dtgProduct.CurrentCell.Value == DBNull.Value) || ((int)dtgProduct.CurrentCell.Value != (int)cbo.SelectedValue))
                && dtgProduct.CurrentCell.ColumnIndex == dtgProduct.Columns["colProduct"].Index)
            {
                m_EnabledEvent = false;
                int productId = Convert.ToInt32(cbo.SelectedValue);
                var product = m_Products.Where(x => x.Id == productId).FirstOrDefault();
                dtgProduct.CurrentRow.Cells["colProductType"].Value = product.ProductTypeId;
                dtgProduct.CurrentRow.Cells["colProducer"].Value = product.ProducerId;
                dtgProduct.CurrentRow.Cells["colProduct"].Value = product.Id;
                dtgProduct.CurrentRow.Cells["colLatestInputPrice"].Value = product.LatestInputPrice;
                dtgProduct.CurrentRow.Cells["colSalePrice"].Value = product.SalePrice;
                m_DataChanged = true;
                m_EnabledEvent = true;
            }
        }

        private void item_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void dtgProduct_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (m_EnabledEvent && e.ColumnIndex != dtgProduct["colRowNumber", e.RowIndex].ColumnIndex)
            {
                m_EnabledEvent = false;
                if (dtgProduct[e.ColumnIndex, e.RowIndex].Value != null)
                {
                    string temp = dtgProduct[e.ColumnIndex, e.RowIndex].Value.ToString();
                    if (e.ColumnIndex == dtgProduct.Columns["colProduct"].Index ||
                        e.ColumnIndex == dtgProduct.Columns["colAmount"].Index ||
                        e.ColumnIndex == dtgProduct.Columns["colInputPrice"].Index)
                    {
                        int cellValue = 0;
                        if (int.TryParse(temp, out cellValue))
                        {
                            if (cellValue > 0)
                            {
                                m_DataChanged = true;
                            }
                        }
                    }
                }

                // Calculate total price column and update total
                var currentRow = dtgProduct.Rows[e.RowIndex];
                if (currentRow != null)
                {
                    if (e.ColumnIndex == currentRow.Cells["colAmount"].ColumnIndex ||
                        e.ColumnIndex == currentRow.Cells["colInputPrice"].ColumnIndex)
                    {
                        dtgProduct["colTotal", e.RowIndex].Value = Convert.ToInt32(dtgProduct["colInputPrice", e.RowIndex].Value) * Convert.ToInt32(dtgProduct["colAmount", e.RowIndex].Value);
                        CalculateTotalAmount();
                    }
                }
                m_EnabledEvent = true;
            }
        }

        private void dtgProduct_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (m_EnabledEvent)
            {
                for (int i = 0; i < dtgProduct.Rows.Count - 1; i++)
                {
                    dtgProduct["colRowNumber", i].Value = i + 1;
                }
                m_DataChanged = false;
            }
        }

        private void dtgProduct_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgProduct.Rows[e.RowIndex].IsNewRow) { return; }

            if (m_EnabledEvent && m_DataChanged)
            {
                for (int i = 0; i < dtgProduct.Rows[e.RowIndex].Cells.Count; i++)
                {
                    dtgProduct.Rows[e.RowIndex].Cells[i].ErrorText = "";
                }
                AddOrUpdateDetail(e.RowIndex);
            }
        }

        private void dtgProduct_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["colProductType"].Value = 0;
            e.Row.Cells["colProducer"].Value = 0;
            e.Row.Cells["colProduct"].Value = 0;
        }

        private void dtgProduct_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.ColumnIndex == dtgProduct.Columns["colProduct"].Index)
            {
                var cellProductType = dtgProduct.Rows[e.RowIndex].Cells["colProductType"];
                var cellProducer = dtgProduct.Rows[e.RowIndex].Cells["colProducer"];
                if (cellProductType.Value != null && cellProducer.Value != null)
                {
                    int productTypeId = Convert.ToInt32(cellProductType.Value);
                    int producerId = Convert.ToInt32(cellProducer.Value);
                    if (productTypeId != 0 || producerId != 0)
                    {
                        IList<Product> products = m_ProductService.GetProductsByTypeAndProducer(productTypeId, producerId);
                        Product allProduct = new Product();
                        allProduct.Id = 0;
                        allProduct.Name = "Tất cả";
                        products.Insert(0, allProduct);
                        DataGridViewComboBoxCell cellProduct = (DataGridViewComboBoxCell)dtgProduct[e.ColumnIndex, e.RowIndex];
                        cellProduct.DataSource = products;
                        cellProduct.ValueMember = "Id";
                        cellProduct.DisplayMember = "Name";

                        // reset value of product column if product type or producer is changed, so the old product is not belong to new colllection of new products
                        var existingProduct = products.Where(p => p.Id == Convert.ToInt32(cellProduct.Value)).FirstOrDefault();
                        if (existingProduct == null)
                        {
                            cellProduct.Value = 0; // reset to "all product"
                        }
                    }
                    else
                    {
                        DataGridViewComboBoxCell cellProduct = (DataGridViewComboBoxCell)dtgProduct[e.ColumnIndex, e.RowIndex];
                        cellProduct.DataSource = m_NewProducts;
                        cellProduct.ValueMember = "Id";
                        cellProduct.DisplayMember = "Name";
                    }
                }
            }
        }

        private void dtgProduct_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dtgProduct.IsCurrentCellDirty)
            {
                int productId = Convert.ToInt32(dtgProduct.CurrentRow.Cells["colProduct"].Value);
                if (productId > 0)
                {
                    dtgProduct.CommitEdit(DataGridViewDataErrorContexts.Commit);
                }
            }
        }

        private void dtgProduct_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dtgProduct.Columns["colProduct"].Index)
            {
                int inProdDetailId = Convert.ToInt32(dtgProduct.Rows[e.RowIndex].Cells["colId"].Value);
                if (inProdDetailId > 0)
                {
                    dtgProduct.Rows[e.RowIndex].Cells["colProduct"].ReadOnly = true;
                    dtgProduct.Rows[e.RowIndex].Cells["colProductType"].ReadOnly = true;
                    dtgProduct.Rows[e.RowIndex].Cells["colProducer"].ReadOnly = true;
                }
            }
        }

        private void dtgProduct_Sorted(object sender, EventArgs e)
        {
            if (m_Mode != FormMode.ADD)
            {
                var view = (DataGridView)sender;
                m_SortOrder = view.SortOrder;
                m_SortColumn = view.SortedColumn.Name;
                bool isCustomSort = false;
                if (m_SortOrder == SortOrder.Ascending)
                {
                    if (m_SortColumn == "colProduct")
                    {
                        m_InProdDetails = m_InProdDetails.OrderBy(x => x.Name).ToList();
                        isCustomSort = true;
                    }
                }
                else
                {
                    if (m_SortColumn == "colProduct")
                    {
                        m_InProdDetails = m_InProdDetails.OrderByDescending(x => x.Name).ToList();
                        isCustomSort = true;
                    }
                }

                if (isCustomSort)
                {
                    if (m_Mode == FormMode.VIEW)
                    {
                        BindDetailsData();
                    }
                    else
                    {
                        BindDetailsDataForUpdate();
                    }
                }
            }
        }
        #endregion DatagridView events

        #region Other events
        private void dtpInputDate_ValueChanged(object sender, EventArgs e)
        {
            if (m_LoadComplete)
            {
                if (m_InProdPaperId != 0)
                {
                    btnUpdate.Enabled = true;
                }
            }
        }

        private void FormInProdPaper_Load(object sender, EventArgs e)
        {
            this.Text += FormMain.GetShopInfo();
            m_EnabledEvent = true;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (m_Mode != FormMode.VIEW)
            {
                if (m_DataChanged)
                {
                    var validateData = ValidateData(dtgProduct.CurrentRow.Index);
                    if (validateData)
                    {
                        DialogResult dialogResult = MessageBox.Show("Dữ liệu thay đổi bạn có muốn lưu lại không ?", "Thông báo", MessageBoxButtons.YesNo);
                        if (dialogResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            AddOrUpdateDetail(dtgProduct.CurrentRow.Index);
                        }
                    }
                }
                if (dtgProduct.Rows.Count == 1 && Convert.ToInt32(dtgProduct.Rows[0].Cells["colId"].Value) == 0)
                {
                    m_InProductService.DeleteInProdPaper(m_InProdPaperId);
                }
            }
            base.OnClosing(e);
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (m_InProdPaperId > 0)
            {
                try
                {
                    InProdPaper paper = new InProdPaper()
                    {
                        Id = m_InProdPaperId,
                        Date = dtpInputDate.Value,
                        CreatedBy = FormMain.s_User.Id
                    };
                    m_InProductService.UpdateInProdPaper(paper);
                    MessageBox.Show("Cập nhật thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btnUpdate.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Cập nhật không thành công vì: " + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    MyLogger.LogException("Lỗi xảy ra khi cập nhật thông tin phiếu nhập kho", ex);
                }
            }
            else
            {
                MessageBox.Show("Phiếu xuất kho chưa được tạo nên không thể cập nhật", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion Other events

        #region Methods
        public void CalculateTotalAmount()
        {
            var rows = dtgProduct.Rows;
            long total = 0;
            if (rows.Count > 0)
            {
                for (int i = 0; i < rows.Count; i++)
                {
                    var row = rows[i];
                    total += Convert.ToInt64(row.Cells["colTotal"].Value);
                }
            }
            lblTotal.Text = total.ToMoney();
        }        

        private void InitData()
        {
            InitProduct();
            InitProducer();
            InitProductType();
        }

        private void InitProduct()
        {
            m_Products = m_ProductService.GetProducts(true);
            Product allProduct = new Product();
            allProduct.Id = 0;
            allProduct.Name = "Tất cả";
            allProduct.IsDeleted = false;
            m_Products.Insert(0, allProduct);
            m_NewProducts = m_Products.Where(x => x.IsDeleted == false).ToList();

            colProduct.DataSource = m_Products;
            colProduct.ValueMember = "Id";
            colProduct.DisplayMember = "Name";
        }

        private void InitProducer()
        {
            m_Producers = m_ProducerService.GetProducers();
            Producer allProducer = new Producer();
            allProducer.Id = 0;
            allProducer.Name = "Tất cả";
            m_Producers.Insert(0, allProducer);

            colProducer.DataSource = m_Producers;
            colProducer.ValueMember = "Id";
            colProducer.DisplayMember = "Name";
        }

        private void InitProductType()
        {
            m_ProductTypes = m_ProductTypeService.GetProductTypes();
            ProductType allProductType = new ProductType();
            allProductType.Id = 0;
            allProductType.Name = "Tất cả";
            m_ProductTypes.Insert(0, allProductType);

            colProductType.DataSource = m_ProductTypes;
            colProductType.ValueMember = "Id";
            colProductType.DisplayMember = "Name";
        }

        private void BindDetailsData()
        {
            dtgProduct.Rows.Clear();
            dtpInputDate.Value = m_InputDate;
            dtpInputDate.Enabled = false;            
            if (m_InProdDetails.Count > 0)
            {
                for (int i = 0; i < m_InProdDetails.Count; i++)
                {
                    var details = m_InProdDetails[i];
                    dtgProduct.Rows.Add((i + 1).ToString());
                    dtgProduct.Rows[i].Cells["colAmount"].Value = details.Amount;
                    dtgProduct.Rows[i].Cells["colInputPrice"].Value = details.InputPrice;
                    dtgProduct.Rows[i].Cells["colTotal"].Value = details.Amount * details.InputPrice;
                    dtgProduct.Rows[i].Cells["colId"].Value = details.ProductDetailId;
                    dtgProduct.Rows[i].Cells["colProduct"].Value = details.ProductId;
                    dtgProduct.Rows[i].Cells["colLatestInputPrice"].Value = details.LatestInputPrice;
                    dtgProduct.Rows[i].Cells["colSalePrice"].Value = details.SalePrice;
                    dtgProduct.Rows[i].Cells["colProduct"].ReadOnly = true;
                }
                CalculateTotalAmount();
            }
        }

        private void BindDetailsDataForUpdate()
        {
            dtgProduct.Rows.Clear();
            dtpInputDate.Value = m_InputDate;
            if (m_InProdDetails.Count > 0)
            {
                for (int i = 0; i < m_InProdDetails.Count; i++)
                {
                    var details = m_InProdDetails[i];
                    var product = m_Products.Where(x => x.Id == details.ProductId).FirstOrDefault();
                    dtgProduct.Rows.Add((i + 1).ToString());
                    dtgProduct.Rows[i].Cells["colAmount"].Value = details.Amount;
                    dtgProduct.Rows[i].Cells["colInputPrice"].Value = details.InputPrice;
                    dtgProduct.Rows[i].Cells["colTotal"].Value = details.Amount * details.InputPrice;
                    dtgProduct.Rows[i].Cells["colId"].Value = details.ProductDetailId;
                    dtgProduct.Rows[i].Cells["colProductType"].Value = product.ProductTypeId;
                    dtgProduct.Rows[i].Cells["colProducer"].Value = product.ProducerId;
                    dtgProduct.Rows[i].Cells["colProduct"].Value = details.ProductId;
                    dtgProduct.Rows[i].Cells["colLatestInputPrice"].Value = details.LatestInputPrice;
                    dtgProduct.Rows[i].Cells["colSalePrice"].Value = details.SalePrice;
                }
                CalculateTotalAmount();
            }
        }

        private bool ValidateData(int rowIndex)
        {
            DataGridViewRow row = dtgProduct.Rows[rowIndex];

            // validate product name
            var data = row.Cells["colProduct"].Value;
            if (data == null || string.IsNullOrWhiteSpace(data.ToString()))
            {
                row.Cells["colProduct"].ErrorText = "Chọn sản phẩm";
                return false;
            }

            // validate product type
            data = row.Cells["colInputPrice"].Value;
            if (data == null || data.ToString() == "0")
            {
                row.Cells["colInputPrice"].ErrorText = "Nhập sản phẩm";
                return false;
            }

            // validate producer
            data = row.Cells["colAmount"].Value;
            if (data == null || data.ToString() == "0")
            {
                row.Cells["colAmount"].ErrorText = "Nhập số lượng";
                return false;
            }

            return true;
        }

        private void AddOrUpdateDetail(int rowIndex)
        {
            var validateData = ValidateData(rowIndex);
            if (validateData)
            {
                int amount = Convert.ToInt32(dtgProduct["colAmount", rowIndex].Value);
                int inputPrice = Convert.ToInt32(dtgProduct["colInputPrice", rowIndex].Value);
                int productId = Convert.ToInt32(dtgProduct["colProduct", rowIndex].Value);
                int detailId = Convert.ToInt32(dtgProduct["colId", rowIndex].Value);
                m_DataChanged = false;
                m_EnabledEvent = false;
                if (detailId == 0)
                {
                    var result = m_InProductService.AddInProdDetail(amount, productId, inputPrice, m_InProdPaperId, FormMain.s_User.Id, dtpInputDate.Value);
                    if (result != null)
                    {
                        m_InProdPaperId = result.InProdPaperId.Value;
                        dtgProduct["colId", rowIndex].Value = result.Id;
                        btnUpdate.Visible = true;
                        btnUpdate.Enabled = false;
                    }
                }
                else
                {
                    var row = dtgProduct.Rows[rowIndex];
                    var returnValue = m_InProductService.UpdateInProdDetail(detailId, amount, inputPrice);
                    if (returnValue == -1)
                    {
                        MessageBox.Show("Cập nhật không thành công, vui lòng thử lại", "Thông báo", 
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        CalculateTotalAmount();
                    }
                }
                if (m_Mode == FormMode.UPDATE)
                {
                    m_InProdDetails = m_InProductService.GetInProdDetails(m_PaperId);
                }
                m_EnabledEvent = true;
            }
        }

        private void PrintBarCode(int numberOfProduct)
        {
            try
            {
                Font printFont = new Font("Arial", 10);
                PrintDocument pd = new PrintDocument();
                m_Copies = numberOfProduct / 2 + numberOfProduct % 2;
                pd.DefaultPageSettings.PaperSize = new PaperSize("Label", 310, LabelHeight * m_Copies);
                pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
                string barcodePrinter = ConfigurationManager.AppSettings["BarcodePrinterName"];
                if (!string.IsNullOrEmpty(barcodePrinter))
                {
                    pd.PrinterSettings.PrinterName = barcodePrinter;
                }
                pd.Print();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs ev)
        {
            int marginTop = 15;
            if (m_ProductItemHasListPrice)
            {
                marginTop = 10;
            }
            for (int i = 0; i < m_Copies; i++)
            {
                ev.Graphics.DrawImage(m_BarCodeImage, 10, marginTop + i * LabelHeight, LabelWidth, LabelHeight);
                ev.Graphics.DrawImage(m_BarCodeImage, 155, marginTop + i * LabelHeight, LabelWidth, LabelHeight);
            }
        }

        #endregion Methods        
    }
}
